package com.atguigu.aliyunvod.service.impl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadFileStreamRequest;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadFileStreamResponse;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.DeleteVideoResponse;
import com.atguigu.aliyunvod.service.VodService;
import com.atguigu.aliyunvod.util.ConstantVodUtils;
import com.atguigu.aliyunvod.util.InitVodClient;
import com.atguigu.commonutils.R;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class VodServiceImpl implements VodService {


    @Override
    public String uploadVIdeo(MultipartFile file)  {

        try {
            //fileName：上传文件原始名称  比如： 01.03.09.mp4
            String fileName = file.getOriginalFilename();
            //title：上传之后显示名称
            String title = fileName.substring(0, fileName.lastIndexOf("."));
//            String title = ("".equals(fileName))?"没有设置视频名称！" :file.getName().substring(0,fileName.lastIndexOf("."));
            //inputStream：上传文件输入流
            InputStream inputStream = file.getInputStream();
            //获取一个请求对象，里面封装了上传到阿里云视频的必要字段或者说参数，API就是通过web请求后面拼下面的参数去发起的，。
            //SDK底层就是封装了API，并且通过httpclient技术去发送请求获取数据。这个技术是安卓等app常用的，因为他们不是通过浏览器做的，所有用这个技术
            UploadStreamRequest request = new UploadStreamRequest(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET, title, fileName, inputStream);
            // 上传接口的实现类
            UploadVideoImpl uploader = new UploadVideoImpl();
            //返回上传后的结果没，如视频id、地址等
            UploadStreamResponse response = uploader.uploadStream(request);

            String videoId = null;
            if(response.isSuccess()){
                videoId=   response.getVideoId();
            }else {//如果设置回调URL无效，不影响视频上传，可以返回VideoId同时会返回错误码。其他情况上传失败时，VideoId为空，此时需要根据返回错误码分析具体错误原因
                videoId = response.getVideoId();
            }

            return videoId;
        } catch (IOException e) {

            throw new GuliException(20001,"上传视频到阿里云失败！");

        }
    }

    @HystrixCommand(fallbackMethod = "outHandler",commandProperties = {
            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="1000")
    })
    //调用阿里云提供的SDK，根据视频ID删除阿里云视频
    @Override
    public R removeVideo(String videoId) {
        try {

//          TimeUnit.MILLISECONDS.sleep(2000);
            //初始化对象
            DefaultAcsClient client = InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
            //创建删除视频的request对象
            DeleteVideoRequest request = new DeleteVideoRequest();
            //向request中设置videoId
            request.setVideoIds(videoId);
            //调用删除方法
            DeleteVideoResponse response = client.getAcsResponse(request);
            System.out.print("删除后回传的RequestId = " + response.getRequestId() + "\n");
        } catch (Exception e) {
            throw new GuliException(20001, "删除阿里云视频失败了");

        }
        return R.ok();
    }
    //自身服务降级的方法，如果想用超时或者运行异常就调用该方法
    public R outHandler(String videoId) {
        return R.error().code(20002).message("删除阿里云视频失败，可能是视频ID已经被删除或者响应超时o(╥﹏╥)o");
    }


    //调用阿里云提供的SDK，批量视频ID “批量” 删除阿里云视频
    @Override
    public void removeVideoList(List<String> videoIdList) {

        try {
            //初始化对象
            DefaultAcsClient client = InitVodClient.initVodClient(ConstantVodUtils.ACCESS_KEY_ID, ConstantVodUtils.ACCESS_KEY_SECRET);
            //创建删除视频的request对象
            DeleteVideoRequest request = new DeleteVideoRequest();
            //调用String的工具类将集合或者数组里面的数据，拼起来变成 1，2，3，4的格式方便调用sdk的方法批量删除
            String join = StringUtils.join(videoIdList.toArray(), ",");
            //向request中设置videoId，可以是多个但是得用，分开
            request.setVideoIds(join);
            //调用删除方法
            DeleteVideoResponse response = client.getAcsResponse(request);
//            System.out.print("删除后回传的RequestId = " + response.getRequestId() + "\n");
        } catch (ClientException e) {
            throw new GuliException(20001,"批量删除视频失败");
        }

    }
}
